package com.py.credit.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Classify;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TreeIndexc;
import com.py.credit.service.ClassifyService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping("/category")
public class ClassifyController {

	@Autowired
	private ClassifyService classifyService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@RequestMapping(value = "/queryCategoryForPage.json")
	public RestServiceResult<List<Classify>> queryCategoryForPage(Page page,
			@RequestParam(value = "name", required = false, defaultValue = "") String name,
			@RequestParam(value = "mainType", required = false, defaultValue = "") String mainType) {
		RestServiceResult<List<Classify>> result = new RestServiceResult<List<Classify>>();
		try {
			List<Classify> datas = classifyService.queryCategoryForPage(name, page, mainType);
			result.setData(datas);
			result.setCount(page.getTotalCount());
		} catch (Exception e) {
			result.setMsg("查询失败");
		}
		return result;
	}

	@RequestMapping(value = "/addIndexAndCategory.json")
	@ResponseBody
	public RestServiceResult<Object> add(@RequestParam(value = "tree", required = false, defaultValue = "") String tree,
			@RequestParam(value = "topId", required = false, defaultValue = "") String topId,
			HttpServletRequest request) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		List<Map<String, Object>> treelist = JSON.parseObject(tree, new TypeReference<List<Map<String, Object>>>() {
		});
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchDataController#updataData", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			classifyService.addIndexAndCategory(treelist, user, topId);
			return result;
		} catch (ServiceException e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(e.getMessage());
			ExceptionLogger.error("ClassifyControllerr#addIndexAndCategory.json", "ERROR:" + e.getMessage(), e);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("数据添加异常，请稍后再试！");
			ExceptionLogger.error("ClassifyController#addIndexAndCategory.json", "数据添加异常ERROR:" + e.getMessage(), e);
			return result;
		}

	}

	@RequestMapping(value = "/addTopCategory.json")
	public RestServiceResult<Object> addTopCategory(
			@RequestParam(value = "name", required = false, defaultValue = "") String name,
			@RequestParam(value = "des", required = false, defaultValue = "") String des,
			@RequestParam(value = "sort", required = false, defaultValue = "") Integer sort,
			@RequestParam(value = "mainType", required = false, defaultValue = "") String mainType,
			@RequestParam(value = "relatedCat", required = false, defaultValue = "") String relatedCat,
			HttpServletRequest request) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchDataController#updataData", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			Classify classify = new Classify();
			classify.setName(name);
			classify.setDes(des);
			classify.setSort(sort);
			classify.setMainType(mainType);
			classify.setRelated_Cat(relatedCat);
			String userName = user.getData().getRealName();
			classify.setCjr(userName);
			classify.setXgr(userName);
			if (!StringUtils.isBlank(relatedCat)) {
				if (CollectionUtils.isEmpty(classifyService.getTreeByTopId(relatedCat))) {
					result.setMsg("该引用分类下无可引用数据，请重新勾选引用分类");
					return result;
				}
			}
			classifyService.addTopCategory(classify);
			return result;
		} catch (ServiceException e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(e.getMessage());
			ExceptionLogger.error("ClassifyControllerr#addTopCategory.json", "ERROR:" + e.getMessage(), e);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("数据添加异常，请稍后再试！");
			ExceptionLogger.error("ClassifyController#addTopCategory.json", "数据添加异常ERROR:" + e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/getTopCategory.json")
	public RestServiceResult<List<Classify>> getTopCategory(
			@RequestParam(value = "mainType", required = false, defaultValue = "") String mainType) {
		RestServiceResult<List<Classify>> result = new RestServiceResult<List<Classify>>();
		result.setData(classifyService.getTopCategory(mainType));
		return result;
	}

	@RequestMapping("/deleteCategoryById.json")
	public RestServiceResult<Object> deleteCategoryById(
			@RequestParam(value = "ids", defaultValue = "", required = false) String ids) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			String[] data = ids.split(",");
			List<String> id = ClassifyController.transferArrayToList(data);
			Iterator<String> iter = id.iterator();
			while(iter.hasNext()) {
            if(classifyService.selectCateModelByIdDel(iter.next()) > 0) {
					
            	iter.remove();
			}
			}
			if(!id.isEmpty()) {
					classifyService.deleteCategoryById(id);
					result.setMsg("删除成功");
			}
			if(id.isEmpty()) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("分类与模型关联并启用，不可以删除，删除失败");
			}
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("删除失败");
		}
		return result;
	}

	@RequestMapping("/updateCategory.json")
	public RestServiceResult<Object> updateCategory(
			@RequestParam(value = "des", required = false, defaultValue = "") String des,
			@RequestParam(value = "name", required = false, defaultValue = "") String name,
			@RequestParam(value = "id", required = false, defaultValue = "") String id,
			@RequestParam(value = "mainType", required = false, defaultValue = "") String mainType,
			@RequestParam(value = "sort", required = false, defaultValue = "") int sort, HttpServletRequest request) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchDataController#updataData", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			String userName = user.getData().getRealName();
			Classify classify = new Classify();
			classify.setDes(des);
			classify.setMainType(mainType);
			classify.setName(name);
			classify.setId(id);
			classify.setXgr(userName);
			classify.setSort(sort);
			classifyService.updateCategory(classify);
			result.setMsg("修改成功");
		} catch (Exception e) {
			result.setMsg("修改失败");
		}
		return result;
	}

	@RequestMapping(value = "/getTreeByTopId.json")
	public RestServiceResult<List<TreeIndexc>> getTreeByTopId(
			@RequestParam(value = "id", required = false, defaultValue = "") String id) {
		RestServiceResult<List<TreeIndexc>> result = new RestServiceResult<List<TreeIndexc>>();
		try {
			if (!CollectionUtils.isEmpty(classifyService.getTreeByTopId(id))) {
				List<TreeIndexc> treeList = classifyService.getTreeByTopId(id);
				result.setData(treeList);
			} else {
				Classify classify = classifyService.getCategoryById(id);
				String relatedCat = classify.getRelated_Cat();
				List<TreeIndexc> treeList = classifyService.getTreeByTopId(relatedCat);
				result.setData(treeList);
			}
		} catch (Exception e) {
			result.setMsg("查询失败");
		}
		return result;
	}

	@RequestMapping(value = "/selectOne.json")
	public RestServiceResult<Classify> selectOne(
			@RequestParam(value = "id", required = false, defaultValue = "") String id) {
		RestServiceResult<Classify> result = new RestServiceResult<Classify>();
		try {
			Classify classify = classifyService.getCategoryById(id);
			result.setData(classify);
		} catch (Exception e) {
			result.setMsg("查询失败");
		}
		return result;
	}

	@RequestMapping(value = "/getCateModelByid.json")
	public RestServiceResult<Integer> getCateModelByid(
			@RequestParam(value = "id", required = false, defaultValue = "") String id) {
		RestServiceResult<Integer> result = new RestServiceResult<Integer>();
		try {
			result.setData(classifyService.getCateModelByid(id));
		} catch (Exception e) {
			result.setMsg("查询失败");
		}
		return result;
	}
	
	private static <E>  List<E> transferArrayToList(E[] array){
        List<E> transferedList = new ArrayList<>();
        Arrays.stream(array).forEach(arr -> transferedList.add(arr));
        return transferedList;
}

}
